package com.yx.cloud.activity;

import static com.yx.cloud.fragment.MusicListFragment.CATE_TYPE_SEARCH_SONG;

import android.animation.Animator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.yx.cloud.Interface.BounceCallBack;
import com.yx.cloud.Interface.EventForwardingHelper;
import com.yx.cloud.MyApplication;
import com.yx.cloud.R;
import com.yx.cloud.adapter.MusicAlbumDetailListAdapter;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.databinding.MusicalbumdetailActivityBinding;
import com.yx.cloud.header.NormalBounceHandler;
import com.yx.cloud.product.sdk.tmall.DeviceStatus;
import com.yx.cloud.product.sdk.tmall.MusicInfo;
import com.yx.cloud.product.sdk.tmall.AliGenieSdk;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.DefaultFooter;
import com.yx.cloud.view.DefaultHeader;
import com.iot.common.utils.Event;
import com.yx.cloud.product.sdk.tmall.req.CreateMusicListParam;
import com.yx.cloud.product.sdk.tmall.req.GetListAlbumDetailParam;
import com.yx.cloud.product.sdk.tmall.req.GetMusicListCateContentParam;
import com.yx.cloud.product.sdk.tmall.req.GetMusicListParam;
import com.yx.cloud.product.sdk.tmall.req.SearchContentParam;
import com.iot.common.utils.LogUtils;
import java.util.ArrayList;
import java.util.List;
import org.greenrobot.eventbus.EventBus;import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 专辑列表界面
 */
public class MusicAlbumDetailActivity extends BaseActivity implements View.OnClickListener ,MusicAlbumDetailListAdapter.InnerItemOnclickListener{
    private static final String TAG = "MusicAlbumDetailActivity";
    MusicAlbumDetailListAdapter musicAlbumDetailListAdapter;
    List<MusicInfo> musicInfos;
    private LoadProgressDialog loadProgressDialog;
    private MusicalbumdetailActivityBinding binding;
    private MusicInfo musicInfo;
    private int totalSize;
    private boolean mIsRefresh;

    @Override
    public void onCreate() {
        fullScreen();
        binding = MusicalbumdetailActivityBinding.inflate(getLayoutInflater());
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)binding.rlMusicAlbumTitle.getLayoutParams();
        lp.topMargin = getStatusBarHeight(this);
        binding.rlMusicAlbumTitle.setLayoutParams(lp);
        setContentView(binding.getRoot());
        Intent intent = getIntent();
        String musicInfoStr = intent.getStringExtra("musicInfo");
        musicInfo = new Gson().fromJson(musicInfoStr, MusicInfo.class);
        initData();
        initEvent();
    }

    private int getStatusBarHeight(Activity activity) {
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return activity.getResources().getDimensionPixelSize(resourceId);
        }
        return 150;
    }

    /**
     * 通过设置全屏，设置状态栏透明
     */
    private void fullScreen() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0 全透明实现
            //getWindow.setStatusBarColor(Color.TRANSPARENT)
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4 全透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);

        new Thread(new Runnable() {
            @Override
            public void run() {
                getAlbumDetail();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                getAlbumDetailList(1,20,true);
            }
        }).start();
        showLoadingDialog();
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    private void initData() {
        binding.tvMusicAlbumTitle.setText(musicInfo.getTitle());
        binding.tvMusicName.setText(musicInfo.getTitle());
        binding.tvSinger.setText(musicInfo.getSingers());
        binding.bl.setBounceHandler(new NormalBounceHandler(), binding.albumListview);//设置滚动冲突的控制类
        binding.bl.setEventForwardingHelper(new EventForwardingHelper() {//自定义事件分发处理
            @Override
            public boolean notForwarding(float downX, float downY, float moveX, float moveY) {
                return true;
            }
        });
        binding.bl.setHeaderView(new DefaultHeader(this), binding.flRoot);//设置刷新头，null意味着没有刷新头，不调用该函数意为着空
        binding.bl.setFooterView(new DefaultFooter(this), binding.flRoot);

        musicInfos = new ArrayList<>();
        musicAlbumDetailListAdapter = new MusicAlbumDetailListAdapter(this, musicInfos);
        musicAlbumDetailListAdapter.setOnInnerItemOnClickListener(this);
        binding.albumListview.setAdapter(musicAlbumDetailListAdapter);

        binding.albumListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //播放歌曲
                Intent_utils.enterIntentFromBottom(MusicAlbumDetailActivity.this,MusicPlayingActivity.class);
            }
        });

        binding.ivCleanRecordReturn.setOnClickListener(this);
    }

    private void showLoadingDialog() {
        if (loadProgressDialog != null) {
            if (loadProgressDialog.isShowing()) {
                loadProgressDialog.dismiss();
            }
        }
        loadProgressDialog = new LoadProgressDialog(this, 6);
        loadProgressDialog.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                loadProgressDialog.dismiss();
                ToastUtil.showShort(MusicAlbumDetailActivity.this, R.string.U_T_NetworkTimeout);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        loadProgressDialog.show();
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_cleanRecordReturn:
                Intent_utils.backIntentFromTop(this);
                break;
        }
    }

    private void initEvent() {
        // 设置上拉加载更多
        binding.bl.setBounceCallBack(new BounceCallBack() {
            @Override
            public void startRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if(totalSize > 20){
                            getAlbumDetailList(1,totalSize,true);
                        }else {
                            getAlbumDetailList(1,20,true);
                        }
                    }
                }).start();
            }

            @Override
            public void startLoadingMore() {
                if(totalSize == musicAlbumDetailListAdapter.getCount() && musicAlbumDetailListAdapter.getCount() > 0){
                    GetListAlbumDetailParam param = new GetListAlbumDetailParam();
                    param.setId(musicInfo.getId());
                    param.setTotalSize(totalSize);
                    mIsRefresh = false;
                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_ALBUM_LIST_DETAIL).result(true).extra(param).content(null).send();
                }else {
                    new Thread(() -> {
                        getAlbumDetailList(musicAlbumDetailListAdapter.getCount() / 20 + 1, 20, false);
                    }).start();
                }
            }
        });
    }

    private void getAlbumDetail() {
        //获取专辑指定信息
        long albumId = musicInfo.getId();
        AliGenieSdk.get().getAlbum(albumId);
    }

    private void getAlbumDetailList(int pageNum, int pageSize, final boolean isRefresh) {
        if(musicInfo != null && musicInfo.getRawId().startsWith("PA") || musicInfo.getRawId().startsWith("MC")){
            mIsRefresh = isRefresh;
            GetMusicListParam param = new GetMusicListParam();
            param.setPageNum(pageNum);
            param.setPageSize(pageSize);
            param.setTopicType(musicInfo.getRawId());
            AliGenieSdk.get().getMusicListByTopicId(param);
        }else if(musicInfo != null && musicInfo.getRawId().equals("白噪音")){
            mIsRefresh = isRefresh;
            SearchContentParam searchContentParam = new SearchContentParam();
            searchContentParam.setQuery(musicInfo.getRawId());
            searchContentParam.setPageSize(pageSize);
            searchContentParam.setPageNum(pageNum);
            searchContentParam.setCateId((long)CATE_TYPE_SEARCH_SONG);
            searchContentParam.setCate("music");
            searchContentParam.setSubCate("song");
            searchContentParam.setAlbum(false);
            AliGenieSdk.get().searchContent(searchContentParam);
        }else if(musicInfo != null && musicInfo.getRawId().startsWith("8")){
            mIsRefresh = isRefresh;
            GetMusicListCateContentParam param = new GetMusicListCateContentParam();
            param.setPageNum(pageNum);
            param.setPageSize(pageSize);
            param.setCateId(Long.valueOf(musicInfo.getRawId()));
            param.setAlbum(false);
            AliGenieSdk.get().getMusicListCateContent(param);
        }else {
            //获取专辑列表内容
            mIsRefresh = isRefresh;
            GetListAlbumDetailParam param = new GetListAlbumDetailParam();
            param.setPageNum(pageNum);
            param.setPageSize(pageSize);
            param.setId(musicInfo.getId());
            AliGenieSdk.get().getListAlbumDetail(param);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_ALBUM_DETAIL:
                RequestOptions options = new RequestOptions()
                        .placeholder(R.mipmap.music_cover_default)
                        .bitmapTransform(new RoundedCorners(30));
                if(event.isResult()){
                    MusicInfo musicInfo = (MusicInfo) event.getContent();
                    binding.tvMusicAlbumTitle.setText(musicInfo.getTitle());
                    binding.tvMusicName.setText(musicInfo.getTitle());
                    binding.tvSinger.setText(musicInfo.getSingers());
                    String icon = musicInfo.getCoverUrl();
                    if(icon == null || icon.equals("")){
                        if(this.musicInfo.getCoverDrawableId() != -1){
                            Glide.with(this).load(musicInfo.getCoverDrawableId()).apply(options).into(binding.ivMusicItemIcon);
                        }else {
                            binding.ivMusicItemIcon.setImageResource(R.mipmap.music_cover_default);
                        }
                    }else {
                        Glide.with(this).load(icon).apply(options).into(binding.ivMusicItemIcon);
                    }
                }else {
                    if(this.musicInfo.getCoverDrawableId() != -1){
                        Glide.with(this).load(musicInfo.getCoverDrawableId()).apply(options).into(binding.ivMusicItemIcon);
                    }else {
                        binding.ivMusicItemIcon.setImageResource(R.mipmap.music_cover_default);
                    }
                    String msg = (String)event.getContent();
                    ToastUtil.show(MusicAlbumDetailActivity.this, msg, Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_SEARCH_CONTENT:
            case Event.MESSAGE_TYPE_GET_MUSIC_LIST:
            case Event.MESSAGE_TYPE_GET_ALBUM_LIST_DETAIL:
                hideLoadingDialog();
                if (event.isResult()) {
                    GetListAlbumDetailParam param = (GetListAlbumDetailParam) event.getExtra();
                    if (totalSize == 0 && totalSize != (int) param.getTotalSize()) {
                        totalSize = (int) param.getTotalSize();
                        if (totalSize > 20) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    getAlbumDetailList(1, totalSize, true);
                                }
                            }).start();
                        }
                    }
                    onDataUpdate(event);
                }else {
                    String msg = (String)event.getContent();
                    ToastUtil.show(MusicAlbumDetailActivity.this, msg, Toast.LENGTH_SHORT);
                    if (mIsRefresh) {
                        binding.bl.setRefreshCompleted();
                    } else {
                        binding.bl.setLoadingMoreCompleted();
                    }
                }
                break;
            case Event.MESSAGE_TYPE_CREATE_MUSIC_LIST:
                if(event.isResult()){
                    Intent intent = new Intent(this, MusicPlayingActivity.class);
                    intent.putExtra("musicInfo", new Gson().toJson(musicAlbumDetailListAdapter.getmMusicInfoList().get(musicAlbumDetailListAdapter.getSelectedItem())));
                    startActivity(intent);
                    overridePendingTransition(R.anim.enteralpha,
                            R.anim.default_anim);
                }else {
                    ToastUtil.show(MusicAlbumDetailActivity.this, event.getContent().toString(), Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_GET_CONTENT:
                if(event.isResult()){
                    if(musicInfo.getRawId().equals("白噪音")){
                        MusicInfo musicInfo1 = (MusicInfo) event.getContent();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                createPlayListByMusicInfo(musicInfo1);
                            }
                        }).start();
                    }
                }else {
                    String message = (String)event.getContent();
                    ToastUtil.show(this, message, Toast.LENGTH_SHORT);
                }
                break;
        }
    }

    public void createPlayListByMusicInfo(MusicInfo musicInfo){
        CreateMusicListParam param = new CreateMusicListParam();
        param.setContentType("content");
        param.setPlayIndex(0);
        //列表循环：Repeat；随机：Shuffle；单曲循环：RepeatOne；顺序播放：Normal。
        param.setPlayMode("Normal");
        List<MusicInfo> createList = new ArrayList<>();
        createList.add(musicInfo);
        AliGenieSdk.get().createMusicList(createList, param);
    }

    public void onDataUpdate(Event event) {
        if (event.isResult()) {
            List<MusicInfo> result = (List<MusicInfo>) event.getContent();
            Log.d("music","parse music list");
            parseMusicInfo(result, mIsRefresh);
        }else {
            binding.rlNoMessage.setVisibility(View.VISIBLE);
        }
    }

    private void parseMusicInfo(List<MusicInfo> result, boolean isRefresh) {
        List<MusicInfo> tempList = result;
        if (isRefresh) {
            DeviceStatus deviceStatus = AliGenieSdk.get().getCurrentMusic();
            int playingPos = deviceStatus.getMusicInfo().getPos();
            if(deviceStatus.getMusicInfo().getMusicPlayStatus().equals("play") && playingPos != -1){
                if(musicAlbumDetailListAdapter.getmMusicInfoList() != null && musicAlbumDetailListAdapter.getmMusicInfoList().size() > playingPos){
                    musicAlbumDetailListAdapter.getmMusicInfoList().get(playingPos).setMusicPlayStatus("play");
                    musicAlbumDetailListAdapter.setCurrentPos(playingPos);
                }
            }
            musicAlbumDetailListAdapter.updateMusic(tempList);
            binding.bl.setRefreshCompleted();
        } else {
            //TODO 这里不确定会不会取到错误数据 有新消息或者消息被删了  下标有变化 比如 以前是取10-20  新来了一条消息后 继续取10-20 其实取到的是以前的9-19
            //可能需要做去重和重定位
            musicAlbumDetailListAdapter.addMusic(tempList);
            binding.bl.setLoadingMoreCompleted();
        }
        if (tempList == null || tempList.size() == 0) {
            if (musicAlbumDetailListAdapter.getItemCount() == 0) {
                binding.albumListview.setVisibility(View.GONE);
                binding.rlNoMessage.setVisibility(View.VISIBLE);
            } else {
                ToastUtil.showShort(MyApplication.get(), R.string.U_NoMoreRecords);
            }
        } else {
            binding.albumListview.setVisibility(View.VISIBLE);
            LogUtils.i("getMessageList size--> : " + tempList.size());
            binding.rlNoMessage.setVisibility(View.GONE);
        }
    }

    private void hideLoadingDialog() {
        if (loadProgressDialog != null) {
            if (loadProgressDialog.isShowing()) {
                loadProgressDialog.dismiss();
            }
        }
    }

    @Override
    public void itemClick(View v, int position) {
        if(musicInfo.getRawId().equals("白噪音")){
            new Thread(() -> {
                MusicInfo musicInfo = musicAlbumDetailListAdapter.getItem(position);
                getContentById(musicInfo.getId());
            }).start();
        }else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    createPlayList(position);
                }
            }).start();
        }
    }

    public void getContentById(long id){
        AliGenieSdk.get().getContent(id);
    }

    public void createPlayList(int index) {
        CreateMusicListParam param = new CreateMusicListParam();
        param.setContentType("content");
        param.setPlayIndex(index);
        //列表循环：Repeat；随机：Shuffle；单曲循环：RepeatOne；顺序播放：Normal。
        param.setPlayMode("Normal");
        AliGenieSdk.get().createMusicList(musicAlbumDetailListAdapter.getmMusicInfoList(), param);
    }
}
